import { SUCCESS, login, getUserInfo, logout} from '@/api'
import { BigNumber, deepObjectMerge } from '@/utils'

let userInfo = null
try {
  userInfo = {
    name: "小明",
    mobile: "17522121212",
    nickName: "小明的昵称wx",
    id: "1",
    headImg: require("@/static/img/home/avatar.png"),
    workStatus: 3,
    sign: 0,
    address: '上梅林店'
  }
  // userInfo = JSON.parse(uni.getStorageSync('userInfo') || `{}`)
} catch (ex) {}

const state = () => ({
  token: uni.getStorageSync('token') || '',
  lastLogin: uni.getStorageSync('lastLogin') || '',
  userInfo: userInfo,
  workItems: [{
      value: '1',
      name: '工作中'
    },
    {
      value: '2',
      name: '休息中',
      checked: 'true'
    },
    {
      value: '3',
      name: '调休'
    }
  ]
})

const getters = {
  /*getLang(state) {
    return state.lang
  },*/
}

const mutations = {
  updateToken (state, token) {
    state.token = token
  },
  updateUserInfo (state, userInfo) {
    state.userInfo = userInfo || {}
  },
  updateLastLogin (state, lastLogin) {
	  uni.setStorageSync('lastLogin', lastLogin)
    state.lastLogin = lastLogin
  },
}

const actions = {
  setToken({ commit }, token) {
    if (token) {
      uni.setStorageSync('token', token)
    } else {
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
    }
    commit('updateToken', token)
  },

  setUserInfo({ commit }, userInfo) {
    if (userInfo) {
      uni.setStorageSync('userInfo', JSON.stringify(userInfo))
    } else {
      uni.removeStorageSync('userInfo')
    }
    commit('updateUserInfo', userInfo)
  },

  // user login
  login({ dispatch, commit }, loginInfo) {
    return new Promise((resolve, reject) => {
      login(loginInfo).then(res => {
        if (res.status === SUCCESS) {
          const apiToken = res.data
          dispatch('setToken', apiToken).then(() => {
			      commit('updateLastLogin', loginInfo.mobile)
            resolve(apiToken)
            // dispatch('getUserInfo').then(res2=>{
            //   resolve({apiToken, userInfo:res2})
            // }).catch(res=>{
            //   reject()
            // })

          })
        } else {
          reject()
        }
      })
    })
  },

  // get user info
  getUserInfo({dispatch, commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        if (res.status === SUCCESS) {
		      !res.data.headImg && (res.data.headImg = require('@/static/img/home/avatar.png'))
          dispatch('setUserInfo', res.data).then(() => {
            resolve(res.data)
          })
        } else {
          reject()
        }
      })
    })
  },

  // user logout
  logout({dispatch, commit, state}) {
    logout().then(res=>{
      dispatch('setToken', null),
      dispatch('setUserInfo', null)
      uni.reLaunch({url:'/pages/login/index'})
    })
  },
}

export default {
  namespaced: true,
  getters,
  state,
  mutations,
  actions
}
